package com.strongbj.iot.devices.amazondb.request.handle;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.amazondb.entity.Tag;
import com.strongbj.iot.devices.amazondb.service.MongoDBService;
import com.strongbj.iot.devices.amazonreader.request.message.MQBodyMessage;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

public class BindTagHandle implements IMessageHandle<MQBodyMessage<Object>, Object> {
	private static Logger logger = LogManager.getLogger(BindTagHandle.class.getName());
	private static final String ACTION_CODE = "bindTag";
	private static final String ACTION_CODE_RETURN = "bindTagReturn";
	private MongoDBService mongoDBService = (MongoDBService) ContextUtils.getBean("mongoDBService");
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static final String TOPIC_NAME = "serverReader";

	@Override
	public boolean isHandle(MQBodyMessage<Object> t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		}
		return false;
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQBodyMessage<Object> t) {
		JSONObject object = (JSONObject) t.getPostdata();
		String readerCode = object.getString("readerCode");
		JSONArray array = object.getJSONArray("labs");
		List<String> tagList = array.toJavaList(String.class);
		try {
			if (tagList != null && tagList.size() > 0) {
				for (String tag : tagList) {
					Tag myTag = mongoDBService.findById(tag);
					if (myTag != null) {
						myTag.setReaderCode(readerCode);
					} else {
						myTag = new Tag();
						myTag.setReaderCode(readerCode);
						myTag.setId(tag);
					}
					mongoDBService.save(myTag);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			MQBodyMessage<String> msg = new MQBodyMessage<>();
			msg.setActioncode(ACTION_CODE_RETURN);
			msg.setGUID(t.getGUID());
			msg.setPostdata("绑定失败:" + e.getMessage());
			logger.info("=========bindTag======="+JSON.toJSONString(msg));
			topicSender.send(TOPIC_NAME, JSON.toJSONString(msg));
			return msg;
		}
		MQBodyMessage<String> msg = new MQBodyMessage<>();
		msg.setActioncode(ACTION_CODE_RETURN);
		msg.setGUID(t.getGUID());
		msg.setPostdata("绑定成功");
		logger.info("=========bindTag======="+JSON.toJSONString(msg));
		topicSender.send(TOPIC_NAME, JSON.toJSONString(msg));
		return msg;
	}

}
